package com.neiquan.weiguan.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.neiquan.weiguan.appliction.MyApplication;

import net.neiquan.applibrary.utils.LogC;

public class DBUtil {
    private static DBUtil mInstance;
    private SQLHelper mSQLHelp;
    private SQLiteDatabase mSQLiteDatabase;


    private DBUtil() {
        mSQLHelp = new SQLHelper(MyApplication.getInstance());
        mSQLiteDatabase = mSQLHelp.getWritableDatabase();
    }

    public SQLiteDatabase getWritableDatabase() {
        return mSQLiteDatabase;
    }

    /**
     * 初始化数据库操作DBUtil类
     */
    public static DBUtil getInstance() {
        if (mInstance == null) {
            mInstance = new DBUtil();
        }
        return mInstance;
    }

    /**
     * 关闭数据库
     */
    public void close() {
        if (mSQLHelp != null)
            mSQLHelp.close();
        mSQLHelp = null;
        if (mSQLiteDatabase != null)
            mSQLiteDatabase.close();
        mSQLiteDatabase = null;
        mInstance = null;
    }

    /**
     * 添加数据
     */
    public long insertData(String table, ContentValues values) {
        if (mInstance == null)
            mInstance = new DBUtil();
        long l = mSQLiteDatabase.insert(table, null, values);
        return l;
    }

    /**
     * 更新数据
     *
     * @param values
     * @param whereClause
     * @param whereArgs
     */
    public int updateData(String table, ContentValues values, String whereClause,
                          String[] whereArgs) {
        if (mInstance == null)
            mInstance = new DBUtil();
        int i = mSQLiteDatabase.update(table, values, whereClause,
                whereArgs);
        return i;
    }

    /**
     * 删除数据
     *
     * @param whereClause
     * @param whereArgs
     */
    public int deleteData(String table, String whereClause, String[] whereArgs) {
        if (mInstance == null)
            mInstance = new DBUtil();
        int i = mSQLiteDatabase
                .delete(table, whereClause, whereArgs);
        return i;
    }

    /**
     * 查询数据
     *
     * @param columns
     * @param selection
     * @param selectionArgs
     * @param groupBy
     * @param having
     * @param orderBy
     * @return
     */
    public Cursor selectData(String table, String[] columns, String selection,
                             String[] selectionArgs, String groupBy, String having,
                             String orderBy) {
        if (mInstance == null)
            mInstance = new DBUtil();
        Cursor cursor = mSQLiteDatabase.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
        return cursor;
    }
}